import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/api/common_service.dart';

// import 'package:wanandroid_flutter/ui/search_page.dart';
// import 'package:wanandroid_flutter/components/drawer_widget.dart';
import 'package:wanandroid_flutter/components/public_widget.dart';
import 'package:wanandroid_flutter/components/carousel_widget.dart';

import 'package:wanandroid_flutter/model/article_model.dart';

import 'package:wanandroid_flutter/utils/timeline_util.dart';
import 'package:wanandroid_flutter/utils/router_push_util.dart';

class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  List<Article> _datas;
  int _page = 0;
  bool isAllData = false;
  bool noResult = false;

  ScrollController _scrollController = ScrollController();

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    _datas = List();
    _getData();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print('滑到底部了');

        _getMore();
      }
    });
    super.initState();
  }

  /// ===============================================

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _getData,
      child: ListView.separated(
        itemBuilder: _renderRow,
        separatorBuilder: (BuildContext context, int index) => Container(
              height: 0.5,
              color: Colors.black12,
            ),
        itemCount: _datas.length == 0 ? 1 : _datas.length + 2,
        controller: _scrollController,
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (noResult) return NoResultWidget();
    if (index == 0) {
      return Container(
        height: 200.0,
        color: Theme.of(context).accentColor,
        child: CarouselWidget(),
      );
    }

    if (index - 1 < _datas.length) {
      return GestureDetector(
        onTap: () {
          RouterPush.toWebview(
              context, _datas[index - 1].title, _datas[index - 1].link);
        },
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
              child: Row(
                children: <Widget>[
                  Text(
                    _datas[index - 1].author,
                    style: TextStyle(
                      fontSize: 12.0,
                    ),
                    textAlign: TextAlign.left,
                  ),
                  Expanded(
                    child: Text(
                      TimelineUtil.format(_datas[index - 1].publishTime),
                      style: TextStyle(fontSize: 12.0),
                      textAlign: TextAlign.right,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      _datas[index - 1].title,
                      maxLines: 2,
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(16, 0, 16, 16),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      _datas[index - 1].superChapterName,
                      style: TextStyle(
                        fontSize: 12.0,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    }
    if (isAllData) return null;
    return GetMoreWidget();
  }

  /// ==============================================

  Future<Null> _getData() async {
    _page = 0;

    CommonService().getArticleList((ArticleModel articleModel) {
      setState(() {
        if (articleModel.data.datas.length == 0) {
          noResult = true;
        } else if (articleModel.data.datas.length != 20) {
          isAllData = true;
        }
        _datas = articleModel.data.datas;
      });
    }, _page);
  }

  Future<Null> _getMore() async {
    _page++;

    CommonService().getArticleList((ArticleModel articleModel) {
      setState(() {
        if (articleModel.data.datas.length != 20) {
          isAllData = true;
        }

        _datas.addAll(articleModel.data.datas);
      });
    }, _page);
  }

  // void onSearchClick() async {
  //   await Navigator.of(context)
  //       .push(MaterialPageRoute(builder: (context) => SearchPage()));
  // }

  /// =============================================

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }
}
